package commonFunc

import (
	"chart.zozoo.net/core/myRedis"
	"encoding/json"
	"errors"
	"io/ioutil"
	"net/http"
	"time"
)

type locationRes struct {
	Status    int            `json:"status"`
	Message   string         `json:"message"`
	RequestId string         `json:"request_id"`
	Result    LocationResult `json:"result"`
}

type LocationResult struct {
	Ip       string `json:"ip"`
	Location struct {
		Lat float64 `json:"lat"`
		Lng float64 `json:"lng"`
	} `json:"location"`
	AdInfo struct {
		Nation     string `json:"nation"`
		Province   string `json:"province"`
		City       string `json:"city"`
		District   string `json:"district"`
		Adcode     int64  `json:"adcode"`
		NationCode int64  `json:"nation_code"`
	} `json:"ad_info"`
}

func IpLocation(ip string) (*LocationResult, error) {
	//判断缓存
	key := "address:ip:" + ip + ":json"
	val := myRedis.RedisClient.Get(key).Val()
	if val != "" {
		locationResult := new(LocationResult)
		err := json.Unmarshal([]byte(val), locationResult)
		if err == nil {
			return locationResult, nil
		}
	}

	//从腾讯地图获取
	url := "https://apis.map.qq.com/ws/location/v1/ip?key=DZ6BZ-KKDWO-KU4WR-S4NOD-IEONE-CKBC5&ip=" + ip
	resp, err := http.Get(url)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}

	locationRes := new(locationRes)
	err = json.Unmarshal(body, locationRes)
	if err != nil {
		return nil, err
	}
	if locationRes.Status != 0 {
		return nil, errors.New(locationRes.Message)
	}

	//保存缓存
	locationStr, _ := json.Marshal(locationRes.Result)
	myRedis.RedisClient.Set(key, string(locationStr), time.Hour*24)

	return &locationRes.Result, nil
}
